package fms.msgupcenter.protocols;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.*;
import javax.xml.transform.stream.StreamSource;
import java.io.*;

/**
 * Created with IntelliJ IDEA.
 * User: adcc
 * Date: 14-6-10
 * Time: 上午9:37
 * To change this template use File | Settings | File Templates.
 */
// @XmlSeeAlso({
//         DownLimkFreeProtocol.class,
//         DownLinkRejProtocol.class
//         UplinkAckProtocol.class,
//         UplinkMsgProtocol.class
 //})
@XmlRootElement(name="acars")  //不为空的设置还没实现
public class AcarsProtocol implements Serializable {
    private String version;

     public AcarsProtocol(){
         version = "2.0";
     }
    @XmlAttribute(name="v")
    public String getVersion() {
        return version;
    }

    public void setVersion(String version) {
        this.version = version;
    }

    public static String Serialize(AcarsProtocol protocol) throws Exception {
        String xml = null;
        JAXBContext context = JAXBContext.newInstance(protocol.getClass());
        Marshaller mar = context.createMarshaller();
        mar.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        mar.setProperty(Marshaller.JAXB_FRAGMENT, Boolean.TRUE);
        //mar.setProperty(Marshaller.JAXB_NO_NAMESPACE_SCHEMA_LOCATION, Boolean.TRUE);
        StringWriter writer = new StringWriter();
        writer.write("<?xml version=\"1.0\" encoding=\"utf-8\"?>\n");
        mar.marshal(protocol, writer);
        xml = new String(writer.toString());

//        System.out.println(xml);
        return   xml;
    }

    public static  <T> T Deserialize(String protocol,Class<T> clazz) throws Exception {

        JAXBContext context = JAXBContext.newInstance(clazz);
        Unmarshaller um =context.createUnmarshaller();
        StringReader sr = new StringReader(protocol);
        StreamSource ss = new StreamSource(sr);
        JAXBElement<T> element = um.unmarshal(ss,clazz);
        return element.getValue();
    }
}
